//
//  music_ViewVC.m
//  K-Music
//
//  Created by 林杰良 on 15/12/29.
//  Copyright © 2015年 CHUN. All rights reserved.
//

#import "YYplayerVC.h"
#import "GBCell.h"
#import "pinglunVC.h"
#import "LiWuVc.h"

@interface YYplayerVC ()<UITableViewDataSource,UITableViewDelegate>{
    UITableView * gbTableView;
    NSMutableArray * guibinData;
    UIImageView * music_View;
}

@end

@implementation YYplayerVC


-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden=YES;
    
    [self _resetStreamer];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(_timerAction:) userInfo:nil repeats:YES];
    [_volumeSlider setValue:[DOUAudioStreamer volume]];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBarHidden=NO;
    
    [_timer invalidate];
    [_streamer stop];
    
    [self _cancelStreamer];
    

    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self creatUI];
    [self downloadTheGuiBinData];

}

-(void)creatUI{
    
    music_View =[[UIImageView alloc]initWithFrame:CGRectMake(0, 20, WIDTH, HEIGHT/3)];
    music_View.image=[UIImage imageNamed:@"音乐背景"];
    
    [self.view addSubview: music_View];
    
    [self Music_View_UI];
    
    [music_View setUserInteractionEnabled:YES];
  
    UIButton*leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(20, 20, 23, 19);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back_w"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backTheFirstPage) forControlEvents:UIControlEventTouchUpInside];
    
    [music_View addSubview:leftBtn];

    
    gbTableView=[[UITableView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(music_View.frame), WIDTH, HEIGHT-CGRectGetMaxY(music_View.frame)-40 )];
    gbTableView.delegate=self;
    gbTableView.dataSource=self;
    gbTableView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"tableview"]];
    [self.view addSubview: gbTableView];

    NSArray*textData=@[@"送礼物",@"评论",@"转发"];
    
    for (int i=0; i<3; i++) {
        
        UIButton*topBtn=[[UIButton alloc]initWithFrame:CGRectMake(i*WIDTH/3, HEIGHT-40,WIDTH/3-1, 40)];
        [topBtn setTitle:textData[i] forState:UIControlStateNormal];
        [topBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        topBtn.userInteractionEnabled = YES;
        topBtn.tag=i+100;
        [topBtn addTarget:self action:@selector(TopButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:topBtn];
        
    }
}

-(void)backTheFirstPage{
    
    [self.navigationController popViewControllerAnimated:YES];
  

}

-(void)TopButtonClick:(UIButton*)btn{
    if (btn.tag==100) {
        LiWuVc*lw=[[LiWuVc alloc]init];
        [self.navigationController pushViewController:lw animated:NO];
    }else if(btn.tag==101){
        pinglunVC*pl=[[pinglunVC alloc]init];
        [self.navigationController pushViewController:pl animated:NO];
    }else{
        
    }
}

#pragma mark--下载贵宾席数据

-(void)downloadTheGuiBinData{
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    
    //获取所有的贵宾信息
    NSString *intactURL = [NSString stringWithFormat:@"http://119.29.113.233:8080/api/vip_seat"];
    
    //根据id获取信息
    
    //    NSString *intactURL = [NSString stringWithFormat:@"http://119.29.113.233:8080/api/vip_seat/record_id/%@",_musicData.aid];
    
    
    NSString * token = [FileStorage NSUserDefault_getObjectForKey:access_token];
    
    manager.requestSerializer =[AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:@"application/json"
                     forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[NSString stringWithFormat: @"Bearer %@",token]
                     forHTTPHeaderField:@"Authorization"];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:intactURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary*dic=[NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        
        NSLog(@"成功GET --> %@", dic);
        
        guibinData=[NSMutableArray array];
        
        NSLog(@"resultCode:%@",dic[@"resultCode"]);
        NSArray*content=dic[@"body"][@"content"];
        
        for (NSDictionary *guibin_Datas in content) {
            GuiBin*aa=[[GuiBin alloc]init];
            aa.aid=guibin_Datas[@"avatar"];
            aa.userId=guibin_Datas[@"userId"];
            aa.userAvatar=guibin_Datas[@"userAvatar"];
            aa.recordId=guibin_Datas[@"recordId"];
            aa.price=guibin_Datas[@"price"];
            aa.createdBy=guibin_Datas[@"createdBy"];
            aa.createdDate=guibin_Datas[@"createdDate"];
            aa.lastModifiedBy=guibin_Datas[@"lastModifiedBy"];
            aa.lastModifiedDate=guibin_Datas[@"lastModifiedDate"];
            [aa fixedString];
            [guibinData addObject:aa];
            
        }
        
        [gbTableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
        
    }];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return HEIGHT/15;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH,HEIGHT/4)];
    headerview.backgroundColor = [UIColor clearColor];
    gbTableView.tableHeaderView=headerview;
    
    
    UIImageView*info_VC=[[UIImageView alloc]initWithFrame:CGRectMake(-0.5, 0, WIDTH+1, HEIGHT/4)];
//    info_VC.image=[UIImage imageNamed:@"tableview.png"];
    info_VC.layer.borderColor=[[UIColor whiteColor]CGColor];
    info_VC.layer.borderWidth=.5f;
    [headerview addSubview:info_VC];
    
    
    UIImageView*headImg=[[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 60, 60)];
    [headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_musicData.avatar]]];
//    headImg.image=[UIImage imageNamed:@"stats"];
    [info_VC addSubview:headImg];
    
    
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(80, 10, WIDTH/1.5, 15)];
//    title.text=@"Alliy";
    title.text=[NSString stringWithFormat:@"%@",_musicData.name];
    title.textColor=[UIColor orangeColor];
    [info_VC addSubview:title];
    
    
    
    UILabel *A_Info=[[UILabel alloc]initWithFrame:CGRectMake(80, title.frame.size.height+title.frame.origin.y, WIDTH/1.5, 15)];
    A_Info.font=[UIFont systemFontOfSize:12.0f];
    A_Info.text=[NSString stringWithFormat:@"%@",_musicData.nickName];
    A_Info.textColor=[UIColor whiteColor];
    [info_VC addSubview:A_Info];
    
    
    UILabel *A_fun=[[UILabel alloc]initWithFrame:CGRectMake(80, A_Info.frame.size.height+A_Info.frame.origin.y, WIDTH/1.5, 15)];
    A_fun.text=@"A_fun";
    A_fun.font=[UIFont systemFontOfSize:12.0f];
    A_fun.textColor=[UIColor whiteColor];
    [info_VC addSubview:A_fun];
    
    
    UILabel *A_text=[[UILabel alloc]initWithFrame:CGRectMake(80, A_fun.frame.size.height+A_fun.frame.origin.y+5, WIDTH/1.3, HEIGHT/11)];
    A_text.text=[NSString stringWithFormat:@"%@",_musicData.music_description];
    A_text.textColor=[UIColor grayColor];
    A_text.font=[UIFont systemFontOfSize:13.0f];
    A_text.backgroundColor=[UIColor colorWithWhite:0.8f alpha:0.9f];
    A_text.numberOfLines=0;
    [info_VC addSubview:A_text];
    
    
    
    
    UIView*A_null=[[UIView alloc]initWithFrame:CGRectMake(80, A_text.frame.size.height+A_text.frame.origin.y, WIDTH/1.5, HEIGHT/15)];
    A_null.backgroundColor=[UIColor clearColor];
    [info_VC addSubview:A_null];
    
    NSArray*imgArr=@[@"收听",@"礼物",@"分享",@"评论"];
    NSArray*myarray=@[[NSString stringWithFormat:@"%@",_musicData.totalPlay],[NSString stringWithFormat:@"%@",_musicData.totalGift],[NSString stringWithFormat:@"%@",_musicData.totalShare],[NSString stringWithFormat:@"%@",_musicData.totalComment]];
    
    for (int i=0; i<4; i++) {
        
        UIImageView*PP=[[UIImageView alloc]initWithFrame:CGRectMake(i* WIDTH/1.4/4,10, 30, 20)];
        PP.image=[UIImage imageNamed:imgArr[i]];
        [A_null addSubview:PP];
        
        
        UILabel *A_null_text=[[UILabel alloc]initWithFrame:CGRectMake(PP.frame.size.width+PP.frame.origin.x+2,0, WIDTH/1.5/4, HEIGHT/15)];
        A_null_text.text=myarray[i];
        A_null_text.font=[UIFont systemFontOfSize:11.0f];
        A_null_text.textColor=[UIColor whiteColor];
        [A_null addSubview:A_null_text];
    }
    
    
    UILabel*guibin=[[UILabel alloc]initWithFrame:CGRectMake(0, A_null.frame.size.height+A_null.frame.origin.y, WIDTH+0.9, HEIGHT/12)];
    guibin.text=@"   |贵宾席";
    guibin.layer.borderWidth=0.3f;
    guibin.layer.borderColor=[[UIColor whiteColor]CGColor];
    guibin.textColor=[UIColor orangeColor];
    guibin.font=[UIFont systemFontOfSize:15.0f];
    [info_VC addSubview:guibin];
    
    return headerview;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return guibinData.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString*inf=@"GBCell";
    
    GBCell*cell=[tableView  dequeueReusableCellWithIdentifier:inf];
    
    if (cell == nil) {
        
        cell = [[[NSBundle mainBundle]loadNibNamed:@"GBCell" owner:self options:nil ] firstObject];
        
    }
    GuiBin*gb=[[GuiBin alloc]init];
    
    gb=guibinData[indexPath.row];
    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",gb.userAvatar]] placeholderImage:nil];
    
    [cell.liwuImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",gb.userAvatar]] placeholderImage:nil];

    cell.name.text=[NSString stringWithFormat:@"%@",gb.userId];
    
    cell.backgroundColor=[UIColor clearColor];
    
    return cell;
}


#pragma mark-- Musi-Play --

- (void)Music_View_UI
{
    UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(music_View.frame)-60,WIDTH,60)];
    view.image = [UIImage imageNamed:@"music_background"];
    
    view.userInteractionEnabled = YES;
    
    _buttonPlayPause = [UIButton buttonWithType:UIButtonTypeCustom];
    [_buttonPlayPause setFrame:CGRectMake(0, 5, 50, 30)];
    _buttonPlayPause.centerX = WIDTH/2 ;
//    [_buttonPlayPause setTitle:@"" forState:UIControlStateNormal];
    [_buttonPlayPause setImage:[UIImage imageNamed:@"music_stop"] forState:UIControlStateNormal];
    [_buttonPlayPause addTarget:self action:@selector(_actionPlayPause:) forControlEvents:UIControlEventTouchDown];
    [view addSubview:_buttonPlayPause];
    
    _buttonNext = [UIButton buttonWithType:UIButtonTypeCustom];
    [_buttonNext setFrame:CGRectMake(CGRectGetMaxX(_buttonPlayPause.frame)+50, 5, 50, 30)];
//    [_buttonNext setTitle:@"Next01" forState:UIControlStateNormal];
    [_buttonNext setImage:[UIImage imageNamed:@"music_next"] forState:UIControlStateNormal];
    [_buttonNext addTarget:self action:@selector(_actionNext:) forControlEvents:UIControlEventTouchDown];
    [view addSubview:_buttonNext];
    
    _buttonStop = [UIButton buttonWithType:UIButtonTypeCustom];
    [_buttonStop setFrame:CGRectMake(CGRectGetMinX
                                    (_buttonPlayPause.frame)-100, 5, 50, 30)];
//    [_buttonStop setTitle:@"Stop01" forState:UIControlStateNormal];
    [_buttonStop setImage:[UIImage imageNamed:@"Music_on"] forState:UIControlStateNormal];
    [_buttonStop addTarget:self action:@selector(_actionNext:) forControlEvents:UIControlEventTouchDown];
    [view addSubview:_buttonStop];
    

    
    
    //缓存进度
    _miscLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(view.frame)-10 , CGRectGetWidth([view bounds]), 20.0)];
    [_miscLabel setFont:[UIFont systemFontOfSize:10.0]];
    [_miscLabel setTextColor:[UIColor colorWithWhite:0.5 alpha:1.0]];
    [_miscLabel setTextAlignment:NSTextAlignmentCenter];
    [_miscLabel setLineBreakMode:NSLineBreakByTruncatingTail];
//    [view addSubview:_miscLabel];

    [music_View addSubview:view];
    
    _progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(music_View.frame)-70, WIDTH, 15)];
    [_progressSlider addTarget:self action:@selector(_actionSliderProgress:) forControlEvents:UIControlEventValueChanged];
    
    [_progressSlider setThumbImage:[UIImage imageNamed:@"music_run"] forState:UIControlStateNormal];
    [_progressSlider setTintColor:RGB(0, 0, 0)];
    
    _progressSlider.minimumTrackTintColor=RGB(139, 213, 44);
    
    _progressSlider.maximumTrackTintColor=RGB(255, 255, 255);
    
    [music_View addSubview:_progressSlider];
}

- (void)_cancelStreamer
{
    if (_streamer != nil) {
        [_streamer pause];
        [_streamer removeObserver:self forKeyPath:@"status"];
        [_streamer removeObserver:self forKeyPath:@"duration"];
        [_streamer removeObserver:self forKeyPath:@"bufferingRatio"];
        _streamer = nil;
    }
}

- (void)_resetStreamer
{
    [self _cancelStreamer];
    
    if (0 == [_tracks count])
    {
        [_miscLabel setText:@"(No tracks available)"];
    }
    else
    {
        Track *track = [_tracks objectAtIndex:_currentTrackIndex];
        NSString *title = [NSString stringWithFormat:@"%@ - %@", track.artist, track.title];
        [_titleLabel setText:title];
        
        _streamer = [DOUAudioStreamer streamerWithAudioFile:track];
        [_streamer addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:kStatusKVOKey];
        [_streamer addObserver:self forKeyPath:@"duration" options:NSKeyValueObservingOptionNew context:kDurationKVOKey];
        [_streamer addObserver:self forKeyPath:@"bufferingRatio" options:NSKeyValueObservingOptionNew context:kBufferingRatioKVOKey];
        
        [_streamer play];
        
        [self _updateBufferingStatus];
        [self _setupHintForStreamer];
    }
}

- (void)_setupHintForStreamer
{
    NSUInteger nextIndex = _currentTrackIndex + 1;
    if (nextIndex >= [_tracks count]) {
        nextIndex = 0;
    }
    
    [DOUAudioStreamer setHintWithAudioFile:[_tracks objectAtIndex:nextIndex]];
}

- (void)_timerAction:(id)timer
{
    if ([_streamer duration] == 0.0) {
        [_progressSlider setValue:0.0f animated:NO];
    }
    else {
        [_progressSlider setValue:[_streamer currentTime] / [_streamer duration] animated:YES];
    }
}

- (void)_updateStatus
{
    switch ([_streamer status]) {
        case DOUAudioStreamerPlaying:
            [_statusLabel setText:@"playing"];
//            [_buttonPlayPause setTitle:@"Pause" forState:UIControlStateNormal];
            
            break;
            
        case DOUAudioStreamerPaused:
            [_statusLabel setText:@"paused"];
//            [_buttonPlayPause setTitle:@"Play" forState:UIControlStateNormal];
            break;
            
        case DOUAudioStreamerIdle:
            [_statusLabel setText:@"idle"];
//            [_buttonPlayPause setTitle:@"Play" forState:UIControlStateNormal];
            break;
            
        case DOUAudioStreamerFinished:
            [_statusLabel setText:@"finished"];
            [self _actionNext:nil];
            break;
            
        case DOUAudioStreamerBuffering:
            [_statusLabel setText:@"buffering"];
            break;
            
        case DOUAudioStreamerError:
            [_statusLabel setText:@"error"];
            break;
    }
}

- (void)_updateBufferingStatus
{
    [_miscLabel setText:[NSString stringWithFormat:@"Received %.2f/%.2f MB (%.2f %%), Speed %.2f MB/s", (double)[_streamer receivedLength] / 1024 / 1024, (double)[_streamer expectedLength] / 1024 / 1024, [_streamer bufferingRatio] * 100.0, (double)[_streamer downloadSpeed] / 1024 / 1024]];
    
    if ([_streamer bufferingRatio] >= 1.0) {
        NSLog(@"sha256: %@", [_streamer sha256]);
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == kStatusKVOKey) {
        [self performSelector:@selector(_updateStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else if (context == kDurationKVOKey) {
        [self performSelector:@selector(_timerAction:)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else if (context == kBufferingRatioKVOKey) {
        [self performSelector:@selector(_updateBufferingStatus)
                     onThread:[NSThread mainThread]
                   withObject:nil
                waitUntilDone:NO];
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}



- (void)_actionPlayPause:(id)sender
{
    if ([_streamer status] == DOUAudioStreamerPaused ||
        [_streamer status] == DOUAudioStreamerIdle) {
        [_streamer play];
    }
    else {
        [_streamer pause];
    }
}

- (void)_actionNext:(id)sender
{
    if (++_currentTrackIndex >= [_tracks count]) {
        _currentTrackIndex = 0;
    }
    
    [self _resetStreamer];
}

- (void)_actionStop:(id)sender
{
    [_streamer stop];
}

- (void)_actionSliderProgress:(id)sender
{
    [_streamer setCurrentTime:[_streamer duration] * [_progressSlider value]];
}

- (void)_actionSliderVolume:(id)sender
{
    [DOUAudioStreamer setVolume:[_volumeSlider value]];
}



























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
